package com.qf.service;

import com.qf.dao.SpitDao;
import com.qf.pojo.Spit;
import com.qf.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author 千锋健哥
 */
@Service
public class SpitServiceImpl implements SpitService{

    @Autowired
    private SpitDao spitDao;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void insert(Spit spit) {
        //生成唯一id
        spit.set_id(String.valueOf(idWorker.nextId()));
        spit.setPublishtime(new Date());
        spitDao.insert(spit);
    }

    @Override
    public void update(Spit spit) {
        spit.setPublishtime(new Date());
        spitDao.save(spit);
    }

    @Override
    public void deleteById(String id) {
        spitDao.deleteById(id);
    }

    @Override
    public Spit findOne(String id) {
        Optional<Spit> byId = spitDao.findById(id);
        if (byId != null) {
            return byId.get();
        }
        return null;
    }

    @Override
    public List<Spit> findList(Spit spit) {
        //创建查询对象
        Query query = new Query();

        //创建条件对象, 相当于sql语句中的where条件
        Criteria c1 = Criteria.where("userid").is(spit.getUserid());

        //将条件放入查询对象中
        query.addCriteria(c1);

        //查询并返回结果
        List<Spit> list = mongoTemplate.find(query, Spit.class);
        return list;
    }

}
